const mysql = require("mysql");
const fs = require("fs");
const dayjs = require("dayjs");
const axios = require("axios");
const qs = require("qs");
const config = require("./config");
const { log } = require("console");
//jwt
const jwt = require("jsonwebtoken");
const secretKey = "your_secret_key";
const OpenAI = require("openai");

// 连接到数据库
const database = mysql.createPool(config.mysql_config);

// 登录
module.exports.login = (req, res) => {
  let { uid, password } = req.body;

  let sql = "select * from user where uid=? and password=?";
  database.query(sql, [uid, password], (err, result) => {
    if (err)
      return res.send({
        code: 400,
        msg: "账号或密码不存在！",
      });
    if (result.length >= 1) {
      const user = {
        uid: result[0].uid,
        name: result[0].name,
      };

      const token = jwt.sign(user, secretKey, { expiresIn: "6h" });

      res.send({
        code: 200,
        uid: user.uid,
        name: user.name,
        token: token,
        msg: "登录成功！",
      });
    } else {
      res.send({
        code: 400,
        msg: "账号或密码不存在！",
      });
    }
  });
};

// 注册
module.exports.register = (req, res) => {
  let { uid, password, name } = req.body;

  if (!uid || !password || !name) {
    return res.send({
      code: 400,
      msg: "请提供完整的注册信息！",
    });
  }

  // 先检查用户是否已存在
  let checkSql = "SELECT * FROM user WHERE uid = ?";
  database.query(checkSql, [uid], (err, result) => {
    if (err) {
      return res.send({
        code: 500,
        msg: "数据库查询出错！",
      });
    }

    if (result.length > 0) {
      return res.send({
        code: 400,
        msg: "该用户ID已存在！",
      });
    }

    // 用户不存在，可以注册
    let insertSql = "INSERT INTO user (uid, password, name) VALUES (?, ?, ?)";
    database.query(insertSql, [uid, password, name], (err, result) => {
      if (err) {
        return res.send({
          code: 500,
          msg: "注册失败，数据库错误！",
        });
      }

      if (result.affectedRows === 1) {
        const user = {
          uid: uid,
          name: name,
        };

        const token = jwt.sign(user, secretKey, { expiresIn: "6h" });

        return res.send({
          code: 200,
          uid: user.uid,
          name: user.name,
          token: token,
          msg: "注册并登录成功！",
        });
      } else {
        return res.send({
          code: 500,
          msg: "注册失败！",
        });
      }
    });
  });
};

// 获取对话列表
module.exports.getChatList = (req, res) => {
  let { uid } = req.body;
  let sql = "select * from chatList where uid=? order by id desc";
  database.query(sql, [uid], (err, result) => {
    if (err)
      return res.send({
        code: 400,
        msg: "错误！",
      });
    res.send({
      code: 200,
      data: result,
      msg: "查询成功！",
    });
  });
};

module.exports.getArticle = (req, res) => {
  let { uid } = req.body;
  let sql = "select * from article where uid=? order by id desc";
  database.query(sql, [uid], (err, result) => {
    if (err)
      return res.send({
        code: 400,
        msg: "错误！",
      });
    res.send({
      code: 200,
      data: result,
      msg: "查询成功！",
    });
  });
};

// 获取模板列表
module.exports.getTemplateList = (req, res) => {
  let sql = "select id,brief,title from template";
  database.query(sql, (err, result) => {
    if (err)
      return res.send({
        code: 400,
        msg: "错误！",
      });
    return res.send({
      code: 200,
      msg: "查询成功！",
      data: result,
    });
  });
};

// 生成文章
module.exports.makeArticle = (req, res) => {
  let { uid, temid, topic, wordsNumber } = req.body;
  let sql = "select data from template where id=?";
  database.query(sql, [temid], (err, result) => {
    if (err)
      return res.send({
        code: 400,
        msg: "错误！",
      });
    if (result.length <= 0) {
      return res.send({
        code: 400,
        msg: "参数错误！",
      });
    }

    let templateData = result[0].data;
    console.log(templateData, topic, wordsNumber);
    
    let newArticle = createArticle(templateData, topic, wordsNumber);
    let date = dayjs().format("YYYY-MM-DD hh:mm:ss");

    // 将文章写入到数据库
    let sql = `insert into article (uid,title,content,date,type) values (?,?,?,?,'template')`;
    // console.log(sql)
    database.query(
      sql,
      [uid, topic, newArticle.article, date],
      (err1, res1) => {
        if (err1)
          return res.send({
            code: 400,
            msg: "数据库炸啦！",
          });
        if (res1.affectedRows === 1) {
          newArticle.topic = topic;
          res.send({
            code: 200,
            message: "文章生成成功！",
            data: newArticle,
          });
        }
      }
    );
  });
};

module.exports.chat = async (req, res) => {
  let { content, chat_id } = req.query;
  if (content === null || chat_id === null) {
    return res.send({
      code: 400,
      msg: "参数错误！",
    });
  }
  //定义api地址
  const url = "https://api.moonshot.cn/v1/chat/completions";
  const params = {
    model: "moonshot-v1-8k",
    messages: [
      {
        role: "user",
        content: content,
      },
    ],
    temperature: 0.3,
  };
  let { data: resGpt } = await axios({
    method: "post",
    url: url,
    data: qs.stringify({
      params,
    }),
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey.value}`,
    },
  });
  // let buff = new Buffer(resGpt.choices[0].message.content); // 默认用 utf-8 编码格式解释字符串
  // resGpt.choices[0].message.content = buff.toString('base64');
  res.header("Content-Type", "text/plain;charset=utf-8");
  return res.send(resGpt);
  //   response.data.choices[0].message.content
};

//test
// module.exports.ai = async (req, res) => {
//     let { content, uid, chat_id, type } = req.body
//     let isNew = false
//     if (content === '' || uid === '')
//       return res.send({
//         code: 400,
//         msg: '参数错误！',
//       })
//     if (chat_id === 'new') {
//       chat_id = chat_id === 'new' ? '' : chat_id
//       isNew = true
//     }
//     let date = dayjs().format('YYYY-MM-DD hh:mm:ss')

//     //定义api地址
//     const url = 'https://api.moonshot.cn/v1/chat/completions'
//     // key
//     const apiKey = 'sk-F3IWyRQttdIPn532nj733iY5eFShZLEfx47J9QuyQmMm0DOy'

//     const params = {
//       model: 'moonshot-v1-8k',
//       messages: [
//         {
//           role: 'user',
//           content: content,
//         },
//       ],
//       temperature: 0.3,
//     }

//     let { data: resGpt } = await axios({
//       method: 'post',
//       url: url,
//       data: params,
//       headers: {
//         'Content-Type': 'application/json',
//         'Authorization': `Bearer ${apiKey}`,
//       },

//       // headers: {
//       //   'Authorization': 'Bearer XYnaQUnmADHFadqZBYrzPBbfDklVuSSY',
//       //   'content-type': 'application/x-www-form-urlencoded',
//       // },
//     })
//     console.log(resGpt.choices);

//   }

module.exports.ai = async (req, res) => {
  console.log(req.body);
  
  let { content, uid, chat_id, type, history } = req.body;
  let isNew = false;
  if (content === "" || uid === "")
    return res.send({
      code: 400,
      msg: "参数错误！",
    });
  if (chat_id === "new") {
    let num = randomNum();
    chat_id = chat_id === "new" ? num : chat_id;
    isNew = true;
  }
  let date = dayjs().format("YYYY-MM-DD hh:mm:ss");

  const apiKey = "sk-F3IWyRQttdIPn532nj733iY5eFShZLEfx47J9QuyQmMm0DOy";
  const client = new OpenAI({
    apiKey,
    baseURL: "https://api.moonshot.cn/v1",
  });

  // 定义api地址
  const url = "https://api.moonshot.cn/v1/chat/completions";

  // console.log(content);
  // console.log(history);

  // 将历史记录和当前用户消息合并
  // const messages = history.concat({
  //   role: "user",
  //   content: content,
  // });
  // console.log(messages);

  const params = {
    model: "moonshot-v1-8k",
    messages: history,
    temperature: 0.3,
  };

  try {
    let { data: resGpt } = await axios({
      method: "post",
      url: url,
      data: params,
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
    });
    resGpt.date = date;
    resGpt.chat_id = chat_id;

    // const completion = await client.chat.completions.create({
    //   model: "moonshot-v1-8k",
    //   messages: history,
    // });
    // if (completion.choices && completion.choices.length == 0) {
    //   history = history.concat(completion.choices[0].message);
    // }
    // console.log(JSON.stringify(completion) + '-------')
    console.log(JSON.stringify(resGpt) + '++++++++')

    if (type === "creation") {
      // 将文章写入到数据库
      let sql1 = `insert into article (uid,title,content,date,type) values (?,?,?,?,'ai')`;
      database.query(
        sql1,
        [uid, content, resGpt.choices[0].message.content, date],
        (err1, res1) => {
          if (err1)
            return res.send({
              code: 400,
              msg: "数据库炸啦！",
            });
          if (res1.affectedRows === 1) {
            return res.send(resGpt); // 直接返回 resGpt 的 data 部分
          }
        }
      );
    } else if (type === "chat") {
      // 用户对话记录
      let sql1 = `insert into chatContent (chatid,uid,content,date,type) values (?,?,?,?,'user')`;
      database.query(sql1, [chat_id, uid, content, date], (err1, res1) => {
        if (err1)
          return res.send({
            code: 400,
            msg: "数据库炸啦！1" + err1,
          });

        if (res1.affectedRows === 1) {
          if (isNew) {
            let sql0 = `insert into chatList (chatid,uid,content,date) values (?,?,?,?)`;
            database.query(
              sql0,
              [chat_id, uid, content, date],
              (err0, res0) => {
                if (err0)
                  return res.send({
                    code: 400,
                    msg: "数据库炸啦！2" + err0,
                  });
              }
            );
          }
          // 将回复写入到数据库
          let sql2 = `insert into chatContent (chatid,uid,content,date,type) values (?,?,?,?,'gpt')`;
          database.query(
            sql2,
            [chat_id, uid, resGpt.choices[0].message.content, date],
            (err2, res2) => {
              if (err2)
                return res.send({
                  code: 400,
                  msg: "数据库炸啦！3",
                });
              if (res2.affectedRows === 1) {
                return res.send(resGpt); // 直接返回 resGpt 的 data 部分
              }
            }
          );
        }
      });
    }
  } catch (error) {
    console.error("请求失败：", error);
    return res.send({
      code: 500,
      msg: "请求失败",
    });
  }
};


module.exports.aiRole = async (req, res) => {
  let { content, uid, chat_id, type } = req.body
  let isNew = false
  if (content === '' || uid === '')
    return res.send({
      code: 400,
      msg: '参数错误！',
    })
  if (chat_id === 'new') {
    let num = randomNum()
    chat_id = chat_id === 'new' ? num : chat_id
    isNew = true
  }
  let date = dayjs().format('YYYY-MM-DD hh:mm:ss')

  //定义api地址
  const url = 'https://api.moonshot.cn/v1/chat/completions'
  // key
  const apiKey = 'sk-F3IWyRQttdIPn532nj733iY5eFShZLEfx47J9QuyQmMm0DOy'

  const params = {
    model: 'moonshot-v1-8k',
    messages: [
      {
        role: 'user',
        content: content,
      },
    ],
    temperature: 0.3,
  }

  let { data: resGpt } = await axios({
    method: 'post',
    url: url,
    data: params,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`,
    },

    // headers: {
    //   'Authorization': 'Bearer XYnaQUnmADHFadqZBYrzPBbfDklVuSSY',
    //   'content-type': 'application/x-www-form-urlencoded',
    // },
  })
  resGpt.date = date
  resGpt.chat_id = chat_id

  //   if (resGpt.code === 200) {
  if (type === 'creation') {
    // 将文章写入到数据库
    let sql1 = `insert into article (uid,title,content,date,type) values (?,?,?,?,?)`
    database.query(sql1, [uid, content, resGpt.choices[0].message.content, date,'ai'], (err1, res1) => {
      if (err1)
        return res.send({
          code: 400,
          msg: '数据库炸啦！',
        })
      if (res1.affectedRows === 1) {
        return res.send(resGpt)
      }
    })
  } else if (type === 'chat') {
    // 用户对话记录
    let sql1 = `insert into chatContent (chatid,uid,content,date,type) values (?,?,?,?,'user')`
    database.query(sql1, [chat_id, uid, content, date], (err1, res1) => {
      if (err1)
        return res.send({
          code: 400,
          msg: '数据库炸啦！1' + err1,
        })

      if (res1.affectedRows === 1) {
        console.log(chat_id, uid, resGpt.choices[0].message.content, date)

        if (isNew) {
          let sql0 = `insert into chatList (chatid,uid,content,date) values (?,?,?,?)`
          database.query(sql0, [chat_id, uid, content, date], (err0, res0) => {
            if (err0)
              return res.send({
                code: 400,
                msg: '数据库炸啦！2' + err0,
              })
          })
        }
        // 将回复写入到数据库
        let sql2 = `insert into chatContent (chatid,uid,content,date,type) values (?,?,?,?,'gpt')`
        database.query(
          sql2,
          [chat_id, uid, resGpt.choices[0].message.content, date],
          (err2, res2) => {
            if (err2)
              return res.send({
                code: 400,
                msg: '数据库炸啦！3',
              })
            if (res2.affectedRows === 1) {
              return res.send(resGpt)
            }
          }
        )
      }
    })
    // }
  }
}

module.exports.getChat = (req, res) => {
  let { chat_id } = req.body;
  let sql = "select * from chatContent where chatid=?";
  database.query(sql, [chat_id], (err, result) => {
    if (err)
      return res.send({
        code: 400,
        msg: "错误！",
      });
    res.send({
      code: 200,
      data: result,
      msg: "查询成功！",
    });
  });
};

// 文章生成算法
function createArticle(templateData, topic, worldNumber) {
  if (typeof templateData == "string") {
    var json = templateData;
    json = json.replace(/\n/g, "").replace(/\r/g, ""); //去掉字符串中的换行符
    json = json.replace(/\n/g, "").replace(/\s|\xA0/g, ""); //去掉字符串中的所有空格
    try {
      var templateData = JSON.parse(json);
    } catch (e) {
      let lastIndex = templateData.lastIndexOf(",");
      if (lastIndex != -1) {
        let begin = templateData.substring(0, lastIndex);
        let end = templateData.substring(lastIndex + 1);
        var templateData = JSON.parse(begin + end);
      }
    }
  }
  if (!templateData.footers) {
    templateData.footers = [""];
  }
  if (!templateData.headers) {
    templateData.headers = [""];
  }
  var number = 0;
  let headerDataArr = templateData.headers;
  let headerIndex = getRandomIntInclusive(0, headerDataArr.length - 1);
  var header = headerDataArr[headerIndex];
  var number = header.replaceAll(" ", "").length;
  let footerDataArr = templateData.footers;
  let footerIndex = getRandomIntInclusive(0, footerDataArr.length - 1);
  var footer = footerDataArr[footerIndex];
  var number = footer.replaceAll(" ", "").length + number;
  let middleDataArr = templateData.middles;
  var middle = "";
  while (true) {
    let middleIndex = getRandomIntInclusive(0, middleDataArr.length - 1);
    let middleItem = middleDataArr[middleIndex];
    var number =
      number +
      middleItem.replaceAll(" ", "").replaceAll("\n\n&emsp;&emsp;", "").length;
    var middle = middle + "\n\n&emsp;&emsp;" + middleItem;
    if (number + 50 > worldNumber) {
      break;
    }
  }
  var article = header + middle + "\n\n&emsp;&emsp;" + footer;
  var article =
    article.replaceAll("x", topic) + "\n\n[声明：本文由智能创作助手生成]";
  return {
    article,
    actualNumber: number,
  };
}

// 生成随机整数数
function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值，含最小值
}

function randomNum() {
  var random1 = parseInt(Math.random() * (15000 - 15) + 10);

  return random1;
}
